package cn.itcast.hotel;

import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.val;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.Map;

@SpringBootTest
public class HotelDemo4Search {
@Autowired
    private IHotelService iHotelService;
    private RestHighLevelClient client=null;
    // 查询所有的语法格式
//        SearchRequest searchRequest = new SearchRequest();
//        // 创建查询类型对象,用于构建查询类型
//        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
//        searchRequest.source(searchSourceBuilder);
    /**
     * 查询的5大类:
     *      查询所有: match_all
     *      全文检索: match mutil_match
     *      精准查询: term range
     *      地理坐标查询: geo_bounding_box geo_distance
     *      复合查询: function_score bool
     */
    /**
     * 查询所有文档信息
     * @throws IOException
     */
    @Test
    public void search01() throws IOException {
        //1.创建请求语义对象
        SearchRequest request = new SearchRequest("hotel");
        // QueryBuilders: 构建查询类型
        request.source().query(QueryBuilders.matchAllQuery());
        //2.发送请求给ES
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //3.处理返回结果
        handleResponse(response);
    }
    //match查询
    //全文检索的match和multi_match查询与match_all的API基本一致。差别是查询条件，也就是query的部分。
    @Test
    void testMatch() throws IOException {
        // 1.准备Request
        SearchRequest request = new SearchRequest("hotel");
        // 2.准备DSL
        request.source()
                .query(QueryBuilders.matchQuery("all", "如家"));
        // 3.发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 4.解析响应
        handleResponse(response);

    }
    //词条查询
    //term：词条精确匹配
    @Test
    void testMatch1() throws IOException {
        // 1.准备Request
        SearchRequest request = new SearchRequest("hotel");
        // 2.准备DSL
        request.source()
                .query(QueryBuilders.termQuery("city","杭州"));
        // 3.发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 4.解析响应
        handleResponse(response);

    }
    //范围查询
    //range：范围查询
    @Test
    void testMatch2() throws IOException {
        // 1.准备Request
        SearchRequest request = new SearchRequest("hotel");
        // 2.准备DSL
        request.source()
                .query(QueryBuilders.rangeQuery("price").gte(100).lte(150));
        // 3.发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 4.解析响应
        handleResponse(response);

    }
    //布尔查询
    //布尔查询是用must、must_not、filter等方式组合其它查询
    @Test
    void testBool() throws IOException {
        // 1.准备Request
        SearchRequest request = new SearchRequest("hotel");
        // 2.准备DSL
        // 2.1.准备BooleanQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 2.2.添加term
        boolQuery.must(QueryBuilders.termQuery("city", "杭州"));
        // 2.3.添加range
        boolQuery.filter(QueryBuilders.rangeQuery("price").lte(250));

        request.source().query(boolQuery);
        // 3.发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 4.解析响应
        handleResponse(response);

    }
    //排序，分页

    //搜索结果的排序和分页是与query同级的参数，因此同样是使用request.source()来设置
    @Test
    void testPageAndSort() throws IOException {
        // 页码，每页大小
        int page = 1, size = 5;

        // 1.准备Request
        SearchRequest request = new SearchRequest("hotel");
        // 2.准备DSL
        // 2.1.query
        request.source().query(QueryBuilders.matchAllQuery());
        // 2.2.排序 sort
        request.source().sort("price", SortOrder.ASC);
        // 2.3.分页 from、size
        request.source().from((page - 1) * size).size(5);
        // 3.发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 4.解析响应
        handleResponse(response);

    }
    //高亮查询
    //- 查询的DSL：其中除了查询条件，还需要添加高亮条件，同样是与query同级。
    //- 结果解析：结果除了要解析_source文档数据，还要解析高亮结果
    @Test
    void testHighlight() throws IOException {
        // 1.准备Request
        SearchRequest request = new SearchRequest("hotel");
        // 2.准备DSL
        // 2.1.query
        request.source().query(QueryBuilders.matchQuery("all", "如家"));
        // 2.2.高亮
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
        // 3.发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 4.解析响应
        handleResponse(response);

    }
//高亮结果解析
    /**- 第一步：从结果中获取source。hit.getSourceAsString()，这部分是非高亮结果，json字符串。还需要反序列为HotelDoc对象
     - 第二步：获取高亮结果。hit.getHighlightFields()，返回值是一个Map，key是高亮字段名称，值是HighlightField对象，代表高亮值
     - 第三步：从map中根据高亮字段名称，获取高亮字段值对象HighlightField
     - 第四步：从HighlightField中获取Fragments，并且转为字符串。这部分就是真正的高亮字符串了
     - 第五步：用高亮的结果替换HotelDoc中的非高亮结果
     * */
    /*private void handleResponse(SearchResponse response) {
        // 4.解析响应
        SearchHits searchHits = response.getHits();
        // 4.1.获取总条数
        long total = searchHits.getTotalHits().value;
        System.out.println("共搜索到" + total + "条数据");
        // 4.2.文档数组
        SearchHit[] hits = searchHits.getHits();
        // 4.3.遍历
        for (SearchHit hit : hits) {
            // 获取文档source
            String json = hit.getSourceAsString();
            // 反序列化
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            // 获取高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)) {
                // 根据字段名获取高亮结果
                HighlightField highlightField = highlightFields.get("name");
                if (highlightField != null) {
                    // 获取高亮值
                    String name = highlightField.getFragments()[0].string();
                    // 覆盖非高亮结果
                    hotelDoc.setName(name);
                }
            }
            System.out.println("hotelDoc = " + hotelDoc);
        }
    }
*/




    /**
     * 处理响应结果
     * @param response
     */
    public void handleResponse(SearchResponse response){
        // 获取命中的所有内容
        SearchHits searchHits = response.getHits();
        // 获取命中的总条数
        long count = searchHits.getTotalHits().value;
        System.out.println("命中的条数为: "+ count);
        // 获取命中的文档对象数组
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            // 解析每一个hit对象得到对应的文档数据
            String json = hit.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            System.out.println(hotelDoc);
        }
    }



    /**
     * 在单元测试执行前执行
     * 创建RestAPI对象
     */
    @BeforeEach
    public void init() {
        client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("192.168.64.3", 9200, "http")
                        //new HttpHost("localhost", 9201, "http")
                ));
        System.out.println(client);
    }


    /**
     * 在单元测试执行前执行
     * 关闭client对象
     */
    @AfterEach
    public void destory() throws Exception {

        if (client != null) {
            client.close();
        }
    }
    }














